<?php
/**
 * @link      http://www.imtfy.com
 * @copyright Copyright (c) 2010-2020 phpWit.
 * @license   http://www.imtfy.com/license
 * @package   imtfy
 * @author    haijun liu mail:875678704@qq.com
 * @version   1.1.1
 */
define('M_START_MEMORY'    ,  memory_get_usage());
define('M_START_TIME'      ,  microtime(true));
//判断程序版本
if(version_compare(PHP_VERSION,'7.0', '<'))exit('程序运行要不小于7.0');
//载入配置文件
require dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'M'.DIRECTORY_SEPARATOR.'config.php';
//初始化session
if(M['session']['start']){startSession();}
header('content-type:text/html; charset=utf-8');
//初始化路由

$router =@$router??(new router)->getrouter();
if($router['func']){
	$newrouter=[];
	try{$newrouter=@$router['func']($router);}catch(\Throwable $e){}
	if($newrouter)array_merge($router,$newrouter);
	unset($router['func']);
}
//判断程序目录
if(is_dir(M['App'].M['ControllersDir'].M['Ds'].$router[0]) && $router[0]){
	define('M_PATH' , $router[0].M['Ds']);
	array_shift($router);
}else{
	define('M_PATH' ,'');
};
//加载目录前置文件
if(is_file(M['App'].M['ControllersDir'].M['Ds'].M_PATH.'__init.php'))include M['App'].M['ControllersDir'].M['Ds'].M_PATH.'__init.php';
//加载主运行文件
$controllerName = isset($router[0])?$router[0]:'index';
if(!preg_match('/^([a-z]|[A-Z]|[0-9])+$/Uis', $controllerName)){$controllerName = 'index';}
$controllerFile = M['App'].M['ControllersDir'].M['Ds'].M_PATH.$controllerName.'.php';
if(!is_file($controllerFile)){
	$controllerName = 'index';
	$controllerFile = M['App'].M['ControllersDir'].M['Ds'].M_PATH.'index.php';
}
require $controllerFile;unset($controllerFile);
//加载方法
if(!defined('M_C'))define('M_C', $controllerName);
unset($controllerName);
$methodName = isset($router[1])?$router[1]:'index';
if(!preg_match('/^([a-z]|[A-Z]|[0-9])+$/Uis', $methodName)){$methodName = 'index';} 
if(!function_exists(M_C.'\\'.$methodName))$methodName = 'index';
define('M_M', $methodName);unset($methodName);
array_shift($router);
array_shift($router);
$GLOBALS['gets']=$router;unset($router);
//初始化超全局函数
M__init();
//内部初始化
if(function_exists(M_C.'\\__init'))(M_C.'\\__init')();
//调用方法
if(function_exists(M_C.'\\'.M_M))(M_C.'\\'.M_M)();unset($MM);
M_runLog();
//全局初始化函数
function M__init(){
	if(M['PostFilter'] && !empty($_POST)){$_POST = str_replace(array('<','>', '"', "'"),array('&lt;','&gt;', '&quot;', ''), $_POST);}
	//过滤GET
	if(!empty($_GET)){$_GET = str_replace(array('<','>', '"', "'"),array('&lt;','&gt;', '&quot;',''), $_GET);}
	if(!empty($GLOBALS['gets'])){
		$GLOBALS['gets'] = str_replace(array('<','>', '"', "'"),array('&lt;','&gt;', '&quot;',''), $GLOBALS['gets']);
		foreach($GLOBALS['gets'] as $v){
			if(@strpos($v,'=')>0){
				$ev=explode('=',$v);if(count($ev)==2)$GLOBALS['gets'][$ev[0]]=$ev[1];
			}
		}
	}
}

class router{
	public $router=[];
	public function __construct(){
		$path=M_getPath();
		if(substr($path,0,1)!='/') {$path='/'.$path;}
		$path=str_replace("//","/",$path);
		$noarguri=explode('?',$path);
		$GLOBALS['no_arg_uri']=$noarguri[0];
		if($GLOBALS['no_arg_uri']=='/'.M['IndexName']) {$GLOBALS['no_arg_uri']='/';}
		@header(base64_decode('WC1Qb3dlcmVkLUJ5OmltdGZ5LmNvbQ=='));
		if(M['RouterStart']){
			global $routes;
			if(!$routes){goto moren;}
			if(is_object($routes))$routes=$routes();
		$site='';
		foreach($routes as $routerkey=>$routervalue) {
			if(\is_string($routervalue)){$routervalue=\json_decode($routervalue,1);}
			$ifmatch=true;
			
			if(isset($routervalue['domain'])) {$ifmatch=$this->macthdomain($routervalue['domain']);}
			
			if($ifmatch){
				//站点全匹配
				if(isset($routervalue['site'])){$site=$routervalue['site'];}
				$this->router['func']=@$routervalue['func'];
				$this->router['data']=@$routervalue['data']?$routervalue['data']:'';
			}
			if(!isset($routervalue['uri'])){continue;}
			if($this->matchuris($routervalue['uri'],$path)===true) {
				//解析RES
				//res= [/APP目录]/控制器文件/函数
				if(substr($routervalue['res'],0,1)=='/') {$routervalue['res']=substr($routervalue['res'],1);}
				
				$this->router=explode('/',$routervalue['res']);
				$this->router['func']=@$routervalue['func'];	
				$this->router['data']=@$routervalue['data']?$routervalue['data']:'';
				if($site){
					if(!$this->router[0]){
						$this->router[0]=$site;
					}else{
						array_unshift($this->router,$site);
					}
				}
				return;
			}
		}
		//默认route;
		}
		moren:
		$dpath=$GLOBALS['no_arg_uri'];
		if(M['Suffix']){$dpath = str_replace(M['Suffix'], '', $dpath);}
		$res = explode('/', $dpath);
		if(empty($res[0])){array_shift($res);}
		$this->router=array_merge($res,$this->router);
		if(!$this->router['func'])$this->router['func']='defRouter';
		if(!$this->router['data'])$this->router['data']='';
		if($site){array_unshift($this->router,$site);}
	}
	function getrouter(){
		return $this->router;
	}
	//判断入口域名规则
	function macthdomain($domains) {
		if(!is_array($domains)) {
			if(empty($domains)) {Return true;}
			$domains=explode(';',strtolower($domains));
		}
		foreach($domains as $val) {
			$val=strtolower(trim($val));
			if($val==$this->servername()) {Return true;}
			if($val=='*') {Return true;}
			$thisstripos=stripos($val,'*');
			if($thisstripos===false) {}else {
				$topdomain=substr($val,$thisstripos+1,strlen($val)-$thisstripos);
				if(substr($this->servername(),-strlen($topdomain))==$topdomain) {Return true;}
				if('*.'.$this->servername()==$val)Return true;
			}
		}
		Return false;
	}
	
	function matchuris($uris,$uri) {
		if(!is_array($uris)) {
			$uris=explode(';',$uris);
		}
		foreach($uris as $val) {
			if(!empty($val)) {
				if(strpos($val,'?')===false) {
					$uri=$GLOBALS['no_arg_uri'];
				}
				if($this->matchuri($val,$uri)===true) {
					Return true;
				}
			}
		}
		Return false;
	}
	//路由匹配
	function matchuri($preguri,$uri) {
		$preguri=urlencode($preguri);
		$preguri=$this->uridecode($preguri);
		if($preguri==$uri && strpos($preguri,'(')===false && strpos($preguri,'[')===false && strpos($preguri,'{')===false) {
			Return true;
		}
		preg_match_all('/[{|\[|(](.*)[}|\]|)]/U',$preguri,$getarray);
		$newrouteruri=$preguri;
		if(count($getarray)>0) {
			foreach($getarray[0] as $getkey=>$getval) {
				if(substr($getval,0,1)=='{') {
					//$newrouteruri=str_replace($getval,'(.+)',$newrouteruri);((?!\/).+)
					$newrouteruri=str_replace($getval,'{{*}}',$newrouteruri);
				}
				if(substr($getval,0,1)=='(') {
					$newrouteruri=str_replace($getval,'([0-9]+)',$newrouteruri);
				}
				if(substr($getval,0,1)=='[') {
					$newrouteruri=str_replace($getval,'([a-zA-Z0-9_]+)',$newrouteruri);
				}
			}
			$newrouteruri=str_replace('/',"\\/",$newrouteruri);
			$newrouteruri=str_replace('?',"\?",$newrouteruri);
			$newrouteruri=str_replace('{{*}}',"((?!\/).+)",$newrouteruri);
			preg_match_all('/'.'startofuri-'.$newrouteruri.'-endofuri'.'/','startofuri-'.$uri.'-endofuri',$ifmatch);
			if(isset($ifmatch[1][0])) {
				foreach($getarray[1] as $getkey=>$getval) {
					$_GET[$getval]=urldecode($ifmatch[1+$getkey][0]);
				}
				Return true;
			}else {
				Return false;
			}
		}else {
			Return false;
		}
	}
	function uridecode($uri) {
		$uri=str_replace('%28','(',$uri);
		$uri=str_replace('%29',')',$uri);
		$uri=str_replace('%7B','{',$uri);
		$uri=str_replace('%7D','}',$uri);
		$uri=str_replace('%5B','[',$uri);
		$uri=str_replace('%5D',']',$uri);
		$uri=str_replace('%2F','/',$uri);
		$uri=str_replace('%3F','?',$uri);
		$uri=str_replace('%3D','=',$uri);
		$uri=str_replace('%26','&',$uri);
		$uri=str_replace('+','%20',$uri);
		$uri=str_replace('%25','%',$uri);
		Return $uri;
	}
	//域名整理
	function servername() {
		if(!isset($_SERVER['S_NAME'])) {
			if(isset($_SERVER['HTTP_HOST'])){
				$thisserver_names=explode(':',$_SERVER['HTTP_HOST']);
				$_SERVER['S_NAME']=$thisserver_names[0];
			}else {
				$_SERVER['S_NAME']=$_SERVER['SERVER_NAME'];
			}
			$_SERVER['S_NAME']=strtolower($_SERVER['S_NAME']);
		}
		Return $_SERVER['S_NAME'];
	}
}



